import {
  indexApi
} from '../../../api/index';
import {
  request
} from '../../../utils/request';
Page({
  data: {
    defaultData: {
      title: "商品列表",
      imageSrc: "/images/back.png",
      isBackToPreviousPage: true
    },
    active: 0,
    menuTwo: [],
    menuThree: [],
    serviceType: null,
    activeKey: 0,
    productNumber: 0,
    totalQuantity: 0,
    totalPrice: 0,
    selectedProducts: [],
    pageNum: 1,
    pageSize: 12,
    serviceTypeId: 0,
    loading: false,
    lastPage: false,
    fromPage: null,
    modifiedProducts: [],
    originalPrice: {},
    programme: {},
    // priceModel:null
    showCustomPrice: false,
    priceName: "",
    customPrice: {},
    customProductPrice: [],
  },

  onLoad(options) {
    if (options.serviceTypeName) {
      const serviceType = JSON.parse(decodeURIComponent(options.serviceTypeName));
      this.setData({
        serviceType
      });
    }

    const programme = wx.getStorageSync('programmeData');
    if (programme) {
      this.setData({
        programme,
        fromPage:options.fromPage
      });
      console.log('收到的 programme 数据:', this.data.programme);
      wx.removeStorageSync('programmeData');
    }
    // priceModel
    // if (options.programme) {
    //   console.log("options.programme",options.programme);
    //   this.setData({
    //     programme:options.programme
    //   });
    // }

    this.handleFirst();
    if ( this.data.programme.priceModel == 2 || options.fromPage == 2 ) {
      this.getCustomPrice()
    }

    this.setData({
      fromPage: options.fromPage,
    })
  },

  // 显示弹窗并初始化价格选项
  showPopup(event) {
    const product = event.currentTarget.dataset.product;
    console.log("product", product);
    // const id = product.id ? product.id : "";
    this.setData({
      show: true,
      priceOptions: {
        cmId: product.id,
        id: product.id ? product.id : "",
        productId: product.productId,
        installationPrice: product.installationPrice || 0,
        debuggingPrice: product.debuggingPrice || 0,
        productPrice: product.productPrice || 0,
        serviceFee: product.serviceFee || 0,
      },
      originalPrice: {
        cmId: product.id,
        id: product.id ? product.id : "",
        productId: product.productId,
        installationPrice: product.installationPrice,
        debuggingPrice: product.debuggingPrice,
        productPrice: product.productPrice,
        serviceFee: product.serviceFee,
      },

    });
    console.log("showPopup", this.data.priceOptions);
  },

  onPriceChange(event) {
    const {
      field
    } = event.currentTarget.dataset;
    const value = event.detail;
    this.setData({
      [`priceOptions.${field}`]: Number(value)
    });
    console.log("onPriceChange", this.data.priceOptions);
  },



  // 关闭弹窗
  onClose() {
    this.setData({
      show: false
    });
  },


  //修改商品价格
  async confirmPriceOptions() {
    const {
      priceOptions,
      modifiedProducts,
      customPrice
    } = this.data;

    priceOptions.cmId = customPrice.id;
    // priceOptions.id = '';
    console.log("priceOptions", this.data.priceOptions);

    try {
      const res = await request({
        url: indexApi.addOrUpdateCustomPriceItemApi(),
        method: "POST",
        data: priceOptions
      });
      console.log("价格修改成功", res.data);
      wx.showToast({
        title: '价格修改成功',
        icon: 'none'
      });
      // 更新已修改商品的列表
      console.log("res");
      this.setData({
        modifiedProducts: [...modifiedProducts, priceOptions.productId]
      });
      this.getCustomPriceItems()
      // this.replaceProduct()
    } catch (error) {
      console.error("Error:", error);
    }
  },


  backup() {
    wx.navigateBack({
      delta: 1
    });
  },

  //修改价格体系名字
  customPriceChange(e) {
    this.setData({
      priceName: e.detail
    });
    console.log("priceName", this.data.priceName);
  },

  //确认价格体系名字
  onConfirmPriceName() {
    if (this.data.priceName.trim() === "") {
      wx.showToast({
        title: "请输入价格体系名称",
        icon: "none",
      });
      return;
    }
    this.addOrUpdateCustomPrice()
  },

  //获取价格体系
  async getCustomPrice() {
    try {
      const res = await request({
        url: indexApi.getCustomPriceApi(),
        data: {}
      });

      if (res.data == null) {
        this.setData({
          showCustomPrice: true
        })
      } else {
        this.setData({
          customPrice: res.data[0]
        })
        console.log("获取价格体系", this.data.customPrice);
      }

      this.getCustomPriceItems()
    } catch (error) {
      console.error("Error:", error);
    }
  },

  //上传价格体系
  async addOrUpdateCustomPrice() {
    const ccustomPriceEntity = {
      priceName: this.data.priceName
    }
    console.log("ccustomPriceEntity", ccustomPriceEntity);
    try {
      const res = await request({
        url: indexApi.addOrUpdateCustomPriceApi(),
        method: "POST",
        data: ccustomPriceEntity
      });
      console.log("上传价格体系", res.data);
      wx.showToast({
        title: "价格体系创建成功",
        icon: "none",
      });
      this.getCustomPriceItems()
    } catch (error) {
      console.error("Error:", error);
    }
  },

  async handleFirst() {
    const id = this.data.serviceType.serviceTypeId;
    console.log("this.data.serviceType.serviceTypeId",id);
    try {
      const res = await request({
        url: indexApi.productLeftApi(id),
        data: {}
      });
      if (res.data && res.data.length > 0) {
        this.setData({
          menuTwo: res.data,
          activeKey: 0,
          serviceTypeId: res.data[0].serviceTypeId
        });
        this.handleTwo();
      }
    } catch (error) {
      console.error("Error:", error);
    }
  },

  //获取价格体系商品列表
  async getCustomPriceItems() {
    const id = this.data.customPrice.id;
    const pageNum = 1
    const pageSize = 1000
    try {
      const res = await request({
        url: indexApi.getCustomPriceItemsApi(pageNum, pageSize, id),
        data: {}
      });
      this.setData({
        customProductPrice: res.data.records
      }, () => {
        this.replaceProduct()
      })

      console.log("customProductPrice", this.data.customProductPrice);
    } catch (error) {
      console.error("Error:", error);
    }
  },



  async handleTwo(event) {
    const {
      programme
    } = this.data;

    if (event) {
      const id = event.currentTarget.dataset.dataid;
      this.setData({
        serviceTypeId: id,
        pageNum: 1,
        menuThree: [],
        lastPage: false,
        loading: true
      });
    } else {
      if (this.data.lastPage) {
        return;
      }
    }

    const id = this.data.serviceTypeId;
    const reqTemplate = {
      id: id,
      pageNum: this.data.pageNum,
      pageSize: this.data.pageSize
    };

    try {
      const res = await request({
        url: indexApi.productRightApi(id),
        method: "POST",
        data: reqTemplate
      });

      const newProducts = res.data.map(product => {
        let updatedProduct = {
          ...product,
          count: 0,
          // 保存原始价格
          oldProductPrice: Number(product.productPrice),
          oldDebuggingPrice: Number(product.debuggingPrice),
          oldInstallationPrice: Number(product.installationPrice),
          oldServiceFee: Number(product.serviceFee),

          totalProductPrice:0,
          totalDebuggingPrice:0,
          totalInstallationPrice:0,
          totalServiceFee:0,
          totalServiceDuration:0,


        };

        // 使用旧价格进行折扣计算
        if (programme.priceModel == 1 && programme.priceDiscountPdt !== null) {
          updatedProduct.productPrice = (updatedProduct.oldProductPrice * (programme.priceDiscountPdt / 10)).toFixed(2);
        }

        if (programme.priceModel == 1 && programme.priceDiscountSev !== null) {
          updatedProduct.installationPrice = (updatedProduct.oldInstallationPrice * (programme.priceDiscountSev / 10)).toFixed(2);
          updatedProduct.serviceFee = (updatedProduct.oldServiceFee * (programme.priceDiscountSev / 10)).toFixed(2);
          updatedProduct.debuggingPrice = (updatedProduct.oldDebuggingPrice * (programme.priceDiscountSev / 10)).toFixed(2);
        }

        return updatedProduct;
      });

      console.log("newProducts+++++", newProducts);

      this.setData({
        menuThree: this.data.pageNum == 1 ? newProducts : [...this.data.menuThree, ...newProducts],
        loading: false,
        lastPage: newProducts.length < this.data.pageSize
      });

      console.log("menuThree", this.data.menuThree);
    } catch (error) {
      console.error("Error:", error);
      this.setData({
        loading: false
      });
    }
  },

  // 替换数据
  replaceProduct() {
    console.log("==============");
    const {
      customProductPrice,
      menuThree,
      programme,
      fromPage
    } = this.data
    customProductPrice.forEach(customProduct => {
      const menuProduct = menuThree.find(menuItem => menuItem.productId === customProduct.productId);
      if (menuProduct) {
        menuProduct.cmId = customProduct.cmId;
        menuProduct.id = customProduct.id;
        menuProduct.isDel = customProduct.isDel;
        menuProduct.createUserId = customProduct.createUserId;
        menuProduct.productPrice = customProduct.productPrice;
        menuProduct.serviceFee = customProduct.serviceFee;
        menuProduct.debuggingPrice = customProduct.debuggingPrice;
        menuProduct.installationPrice = customProduct.installationPrice;
      }
      console.log("++++++++++++++",programme);
      if (programme.priceModel == 2 && fromPage==1 && programme.priceDiscountPdt !== null) {
        console.log("++++++++++++++============");
        menuProduct.productPrice = (menuProduct.productPrice * (programme.priceDiscountPdt / 10)).toFixed(2);
      }

      if (programme.priceModel == 2 && fromPage==1 && programme.priceDiscountSev !== null) {
        menuProduct.installationPrice = (menuProduct.installationPrice * (programme.priceDiscountSev / 10)).toFixed(2);
        menuProduct.serviceFee = (menuProduct.serviceFee * (programme.priceDiscountSev / 10)).toFixed(2);
        menuProduct.debuggingPrice = (menuProduct.debuggingPrice * (programme.priceDiscountSev / 10)).toFixed(2);
      }
    });
    this.setData({
      menuThree
    })

    console.log("menuThree++++++++++++++++", this.data.menuThree);

  },

  onReachBottom() {
    if (this.data.loading || this.data.lastPage) return;
    this.setData({
      pageNum: this.data.pageNum + 1
    });
    this.handleTwo();
  },

  add(event) {
    const productId = event.currentTarget.dataset.productid;
    const updatedMenuThree = this.data.menuThree.map(product => {
      if (product.productId === productId) {
        return {
          ...product,
          count: product.count + 1
        };
      }
      return product;
    });

    const updatedSelectedProducts = [...this.data.selectedProducts];
    const existingProductIndex = updatedSelectedProducts.findIndex(product => product.productId === productId);
    if (existingProductIndex !== -1) {
      updatedSelectedProducts[existingProductIndex].count += 1;
    } else {
      const selectedProduct = this.data.menuThree.find(product => product.productId === productId);
      updatedSelectedProducts.push({
        ...selectedProduct,
        count: 1
      });
    }

    this.setData({
      menuThree: updatedMenuThree,
      selectedProducts: updatedSelectedProducts
    });
    console.log("selectedProducts", this.data.selectedProducts);
    this.updateTotals();
  },

  reduce(event) {
    const productId = event.currentTarget.dataset.productid;
    const updatedMenuThree = this.data.menuThree.map(product => {
      if (product.productId === productId && product.count > 0) {
        return {
          ...product,
          count: product.count - 1
        };
      }
      return product;
    });

    const updatedSelectedProducts = [...this.data.selectedProducts];
    const existingProductIndex = updatedSelectedProducts.findIndex(product => product.productId === productId);
    if (existingProductIndex !== -1) {
      updatedSelectedProducts[existingProductIndex].count -= 1;
      if (updatedSelectedProducts[existingProductIndex].count === 0) {
        updatedSelectedProducts.splice(existingProductIndex, 1);
      }
    }

    this.setData({
      menuThree: updatedMenuThree,
      selectedProducts: updatedSelectedProducts
    });
    this.updateTotals();
  },

  onStepperChange(event) {
    const productId = event.currentTarget.dataset.productid;
    const count = parseInt(event.detail.value, 10);

    if (isNaN(count) || count < 0) {
      return;
    }

    const updatedMenuThree = this.data.menuThree.map(product => {
      if (product.productId === productId) {
        return {
          ...product,
          count: count
        };
      }
      return product;
    });

    const updatedSelectedProducts = [...this.data.selectedProducts];
    const existingProductIndex = updatedSelectedProducts.findIndex(product => product.productId === productId);
    if (existingProductIndex !== -1) {
      updatedSelectedProducts[existingProductIndex].count = count;
    } else {
      const selectedProduct = this.data.menuThree.find(product => product.productId === productId);
      updatedSelectedProducts.push({
        ...selectedProduct,
        count: count
      });
    }

    this.setData({
      menuThree: updatedMenuThree,
      selectedProducts: updatedSelectedProducts
    });
    this.updateTotals();
  },

  updateTotals() {
    const totalQuantity = this.data.menuThree.reduce((total, product) => total + product.count, 0);
    const totalPrice = this.data.menuThree.reduce((total, product) => total + (product.count * product.productPrice), 0).toFixed(2);
    this.setData({
      totalQuantity,
      totalPrice
    });
  },

  onSubmit() {
    const app = getApp();
    app.globalData.selectedProducts = this.data.selectedProducts;
    console.log("app.globalData.selectedProducts",app.globalData.selectedProducts);
    wx.switchTab({
      url: '/pages/quick/index',
    });
  }
});